package cn.itsource.exception;


import cn.itsource.result.JSONResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;




//@ControllerAdvice + @ResponseBody
//可以理解为是controller的加强
//ExceptionHandler统一异常处理
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public JSONResult runTimeException(Exception e){
        e.printStackTrace();

        return JSONResult.error("系统级别错误！");
    }

    @ExceptionHandler(RuntimeException.class)
    public JSONResult runTimeException(RuntimeException e){
        e.printStackTrace();

        return JSONResult.error(e.getMessage());
    }


    @ExceptionHandler(GlobalException.class)
    public JSONResult globalException(GlobalException e){
        e.printStackTrace();

        return JSONResult.error(e.getMessage(),"5000");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult validateException(MethodArgumentNotValidException e){
        StringBuffer sb = new StringBuffer();
        for (ObjectError allError : e.getBindingResult().getAllErrors()) {
            sb.append(allError.getDefaultMessage()).append(",") ;
        }
        e.printStackTrace();
        return JSONResult.error(sb.toString(),"7000");
    }
}
